import React, { useState, useEffect, useRef } from 'react';
import {
    ArrowLeftOutlined,
    CalendarOutlined,
    ClockCircleOutlined,
    CheckCircleOutlined,
    LoadingOutlined,
    CloseOutlined
} from '@ant-design/icons';
import { CalendarPicker, List, Toast } from 'antd-mobile';
import dayjs from 'dayjs';
import './appointment.css';

// 服务数据
const services = [
    {
        id: '1',
        name: '全身推拿理疗',
        duration: '60分钟',
        originalPrice: 198,
        discountPrice: 158,
        description: '通过专业推拿手法疏通经络，缓解肌肉疲劳',
        img: 'https://picsum.photos/id/177/300/300',
        stock: '充足'
    },
    {
        id: '2',
        name: '肩颈专项调理',
        duration: '45分钟',
        originalPrice: 158,
        discountPrice: 128,
        description: '针对肩颈部位深度放松，改善肩颈僵硬、酸痛',
        img: 'https://picsum.photos/id/180/300/300',
        stock: '紧张'
    },
    {
        id: '3',
        name: '腰椎舒缓养护',
        duration: '45分钟',
        originalPrice: 158,
        discountPrice: 128,
        description: '专注腰椎区域调理，缓解腰椎压力',
        img: 'https://picsum.photos/id/183/300/300',
        stock: '充足'
    }
];

// 生成时段选项
const generateTimeOptions = (selectedDate) => {
    if (!selectedDate) return [];
    
    const timeSegments = [
    "09:00-12:00",
    "12:00-14:00",
    "14:00-17:00",
    "17:00-18:00",
    "18:00-21:00"
    ];

    const isToday = selectedDate === dayjs().format('YYYY-MM-DD');
    const currentHour = dayjs().hour();

    return timeSegments
    .map((segment) => {
      const segmentStartHour = parseInt(segment.split('-')[0].split(':')[0]);
      let isAvailable = true;

      if (isToday && segmentStartHour < currentHour) {
        isAvailable = false;
      }

      return {
        time: segment,
        available: isAvailable
      };
    })
    .filter((item) => item.available);
};

const Appointment = () => {
    // 状态管理
    const [selectedService, setSelectedService] = useState(null);
    const [selectedCalendarDate, setSelectedCalendarDate] = useState(null);
    const [isCalendarVisible, setIsCalendarVisible] = useState(false);
    const [selectedTime, setSelectedTime] = useState('');
    const [timeOptions, setTimeOptions] = useState([]);
    const [isTimeModalVisible, setIsTimeModalVisible] = useState(false);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const modalRef = useRef(null);
    // 存储当天日期（用于验证）
    const today = dayjs().startOf('day').format('YYYY-MM-DD');

   // 选择日期后验证并更新
const handleCalendarConfirm = (date) => {
  if (!date) return;

  const selected = dayjs(date);
  const formattedDate = selected.format('YYYY-MM-DD');

  // 核心验证：如果选择的是过去的日期，强制重置为当天
  if (selected.isBefore(dayjs().startOf('day'))) {
    Toast.show('不能选择过去的日期');
    // 强制设置为当天
    setSelectedCalendarDate(today);
    setIsCalendarVisible(false);
    // 生成当天的时段
    setTimeOptions(generateTimeOptions(today));
    return;
  }

  // 生成当天的时段列表
  const todayTimeOptions = generateTimeOptions(formattedDate);
  
  // 关键逻辑：若当天无可用时段，自动切换到明天
  if (todayTimeOptions.length === 0) {
    const tomorrow = selected.add(1, 'day');
    const tomorrowDate = tomorrow.format('YYYY-MM-DD');
    Toast.show('当天无可用时段，已自动切换到明天');
    setSelectedCalendarDate(tomorrowDate);
    setTimeOptions(generateTimeOptions(tomorrowDate));
  } else {
    // 正常流程：当天有时段，直接设置
    setSelectedCalendarDate(formattedDate);
    setTimeOptions(todayTimeOptions);
  }

  setIsCalendarVisible(false);
  setSelectedTime('');
};

// 生成时段选项（保持原逻辑，无需修改）
const generateTimeOptions = (selectedDate) => {
  if (!selectedDate) return [];

  const timeSegments = [
    "09:00-12:00",
    "12:00-14:00",
    "14:00-17:00",
    "17:00-18:00",
    "18:00-21:00"
  ];

  const isToday = selectedDate === dayjs().format('YYYY-MM-DD');
  const currentHour = dayjs().hour();

  return timeSegments
    .map((segment) => {
      const segmentStartHour = parseInt(segment.split('-')[0].split(':')[0]);
      let isAvailable = true;

      if (isToday && segmentStartHour < currentHour) {
        isAvailable = false;
      }

      return {
        time: segment,
        available: isAvailable
      };
    })
    .filter((item) => item.available);
};

    // 选择服务
    const handleServiceSelect = (service) => {
        setSelectedService(service);
        setSelectedCalendarDate('');
        setSelectedTime('');
        setTimeOptions([]);

        // 滚动到表单区域
        setTimeout(() => {
            const formSection = document.querySelector('.ap_form-section');
            if (formSection) {
                formSection.scrollIntoView({ behavior: 'smooth' });
            }
        }, 300);
    };

    // 打开时段选择模态框
    const openTimeModal = () => {
        if (!selectedCalendarDate) {
            Toast.show('请先选择预约日期');
            return;
        }
        
        const newOptions = generateTimeOptions(selectedCalendarDate);
        setTimeOptions(newOptions);
        
        if (newOptions.length > 0) {
            setIsTimeModalVisible(true);
            document.body.style.overflow = 'hidden';
        } else {
            Toast.show('该日期没有可用时段');
        }
    };

    // 关闭时段选择模态框
    const closeTimeModal = () => {
        setIsTimeModalVisible(false);
        document.body.style.overflow = '';
    };

    // 选择时段
    const handleTimeSelect = (time) => {
        setSelectedTime(time);
        closeTimeModal();
    };

    // 点击模态框外部关闭
    useEffect(() => {
        const handleClickOutside = (event) => {
            if (isTimeModalVisible && modalRef.current && !modalRef.current.contains(event.target)) {
                closeTimeModal();
            }
        };
        
        document.addEventListener('mousedown', handleClickOutside);
        return () => {
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, [isTimeModalVisible]);

    // 提交预约
    const handleSubmit = async () => {
        // 再次验证日期（双重保险）
        if (selectedCalendarDate && dayjs(selectedCalendarDate).isBefore(dayjs().startOf('day'))) {
            Toast.show('选择的日期无效，请重新选择');
            setSelectedCalendarDate('');
            return;
        }

        // 其他验证
        if (!selectedService) {
            Toast.show('请选择预约服务');
            return;
        }
        if (!selectedCalendarDate) {
            Toast.show('请选择预约日期');
            return;
        }
        if (!selectedTime) {
            Toast.show('请选择预约时段');
            return;
        }

        setIsSubmitting(true);
        try {
            await new Promise(resolve => setTimeout(resolve, 1500));
            Toast.show({
                content: (
                    <div style={{ textAlign: 'center' }}>
                        <CheckCircleOutlined style={{ color: '#00B42A', fontSize: '24px', marginBottom: '8px' }} />
                        <div>预约成功！</div>
                        <div style={{ fontSize: '14px', marginTop: '4px' }}>
                            {selectedService.name} | {selectedCalendarDate} {selectedTime}
                        </div>
                    </div>
                ),
                duration: 3000
            });
            resetForm();
        } catch (error) {
            Toast.show('预约失败，请重试');
        } finally {
            setIsSubmitting(false);
        }
    };

    // 重置表单
    const resetForm = () => {
        setSelectedService(null);
        setSelectedCalendarDate(null);
        setSelectedTime('');
        setTimeOptions([]);
    };

    // 返回
    const goBack = () => {
        window.history.back();
    };

    // 日期变化时更新时段
    useEffect(() => {
        if (selectedCalendarDate) {
            // 再次验证日期有效性
            if (dayjs(selectedCalendarDate).isBefore(dayjs().startOf('day'))) {
                setSelectedCalendarDate('');
                Toast.show('日期已过期，请重新选择');
                return;
            }
            setTimeOptions(generateTimeOptions(selectedCalendarDate));
        } else {
            setTimeOptions([]);
        }
    }, [selectedCalendarDate]);

    // 构建时段选择项
    const renderTimeItems = () => {
        return timeOptions.map(item => (
            <div
                key={item.time}
                onClick={() => item.available && handleTimeSelect(item.time)}
                style={{
                    padding: '16px',
                    textAlign: 'center',
                    fontSize: '16px',
                    cursor: item.available ? 'pointer' : 'not-allowed',
                    color: item.available ? '#333' : '#999',
                    backgroundColor: selectedTime === item.time ? '#f5f5f5' : 'transparent',
                    borderBottom: '1px solid #eee'
                }}
            >
                {item.time}
                {!item.available && <span style={{ marginLeft: '8px', fontSize: '14px', color: '#ff4d4f' }}>已满</span>}
            </div>
        ));
    };

    return (
        <div className="ap_appointment-page">
            {/* 顶部导航 */}
            <header className="ap_detail-header">
              
                <i className="fa fa-arrow-left"  style={{ color: '#8B5A2B', fontSize: '20px',cursor:'pointer' }} onClick={goBack}></i>
                <h1 className="ap_header-title">理疗预约</h1>
                <div className="ap_header-placeholder" style={{'width':'20px'}}></div>
            </header>

            {/* 步骤指示器 */}
            <div className="ap_step-indicator">
                <div className={`ap_step ${selectedService ? 'ap_step-active' : ''}`}>
                    <div className="ap_step-icon"><CalendarOutlined /></div>
                    <div className="ap_step-text">选择服务</div>
                </div>
                <div className={`ap_step-line ${selectedService ? 'ap_line-active' : ''}`}></div>
                <div className={`ap_step ${selectedCalendarDate && selectedTime ? 'ap_step-active' : ''}`}>
                    <div className="ap_step-icon"><ClockCircleOutlined /></div>
                    <div className="ap_step-text">选择时间</div>
                </div>
                <div className={`ap_step-line ${selectedCalendarDate && selectedTime ? 'ap_line-active' : ''}`}></div>
                <div className={`ap_step ${isSubmitting ? 'ap_step-loading' : selectedCalendarDate && selectedTime ? 'ap_step-active' : ''}`}>
                    <div className="ap_step-icon">{isSubmitting ? <LoadingOutlined spin /> : <CheckCircleOutlined />}</div>
                    <div className="ap_step-text">完成预约</div>
                </div>
            </div>

            {/* 服务列表 */}
            <div className="ap_service-list">
                <h2 className="ap_section-title">理疗服务项目</h2>

                {services.map((service) => (
                    <div
                        key={service.id}
                        className={`ap_service-item ${selectedService?.id === service.id ? 'ap_service-selected' : ''}`}
                        onClick={() => handleServiceSelect(service)}
                    >
                        <div className="ap_service-img-container">
                            <img
                                src={service.img}
                                alt={service.name}
                                onError={(e) => e.target.src = 'https://picsum.photos/id/1005/300/300'}
                                className="ap_service-img"
                            />
                        </div>

                        <div className="ap_service-desc">
                            <h4 className="ap_service-name">{service.name}</h4>
                            <p className="ap_service-desc-text">{service.description}</p>

                            <div className="ap_service-meta">
                                <span className="ap_meta-text">
                                    <ClockCircleOutlined style={{ fontSize: '13px', marginRight: '3px' }} />
                                    {service.duration}
                                </span>
                                <div className="ap_price-group">
                                    <span className="ap_meta-original-price">¥{service.originalPrice}</span>
                                    <span className="ap_meta-discount-price">¥{service.discountPrice}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                ))}
            </div>

            {/* 预约表单 */}
            {selectedService && (
                <div className="ap_form-section">
                    <h3 className="ap_form-title">
                        <CalendarOutlined style={{ marginRight: '6px' }} />
                        填写预约信息
                    </h3>
                    <List className="ap_form-list">
                        {/* 日期选择 */}
                        <List.Item
                            prefix={<CalendarOutlined className="ap_list-icon" />}
                            className="ap_list-item"
                            onClick={() => setIsCalendarVisible(true)}
                        >
                            <div className="ap_picker-display">
                                {selectedCalendarDate ? selectedCalendarDate : '请选择预约日期'}
                            </div>
                        </List.Item>

                        {/* 组件层面限制 + 明确提示 */}
                        <CalendarPicker
                            visible={isCalendarVisible}
                            onConfirm={handleCalendarConfirm}
                            onCancel={() => setIsCalendarVisible(false)}
                            minDate={new Date(dayjs().startOf('day').valueOf())} // 原生Date对象，确保兼容性
                            maxDate={new Date(dayjs().add(7, 'day').valueOf())}
                            defaultValue={new Date(dayjs().startOf('day').valueOf())}
                            // 自定义日期单元格渲染（进一步强化视觉提示）
                            renderDay={(date) => {
                                const isPast = dayjs(date).isBefore(dayjs().startOf('day'));
                                return (
                                    <div style={{
                                        ...(isPast ? { 
                                            color: '#ccc', 
                                            cursor: 'not-allowed',
                                            textDecoration: 'line-through'
                                        } : {})
                                    }}>
                                        {dayjs(date).date()}
                                    </div>
                                );
                            }}
                        />

                        {/* 时段选择 */}
                        <List.Item
                            prefix={<ClockCircleOutlined className="ap_list-icon" />}
                            className="ap_list-item ap_picker-item"
                            onClick={openTimeModal}
                        >
                            <div className="ap_picker-display">
                                {selectedTime ? selectedTime : (selectedCalendarDate ? '请选择预约时段' : '请先选择日期')}
                            </div>
                        </List.Item>
                    </List>

                    {/* 自定义时段选择模态框 */}
                    {isTimeModalVisible && (
                        <>
                            <div 
                                style={{
                                    position: 'fixed',
                                    top: 0,
                                    left: 0,
                                    right: 0,
                                    bottom: 0,
                                    backgroundColor: 'rgba(0, 0, 0, 0.5)',
                                    zIndex: 9998,
                                }}
                                onClick={closeTimeModal}
                            ></div>
                            
                            <div 
                                ref={modalRef}
                                style={{
                                    position: 'fixed',
                                    bottom: 0,
                                    left: 0,
                                    right: 0,
                                    backgroundColor: 'white',
                                    borderRadius: '16px 16px 0 0',
                                    zIndex: 9999,
                                    maxHeight: '80vh',
                                }}
                            >
                                <div style={{
                                    padding: '16px',
                                    display: 'flex',
                                    justifyContent: 'space-between',
                                    alignItems: 'center',
                                    borderBottom: '1px solid #eee'
                                }}>
                                    <h3 style={{ margin: 0, fontSize: '18px' }}>选择预约时段</h3>
                                    <CloseOutlined 
                                        onClick={closeTimeModal}
                                        style={{ fontSize: '20px', color: '#999', cursor: 'pointer' }}
                                    />
                                </div>
                                
                                <div style={{ maxHeight: 'calc(80vh - 60px)', overflowY: 'auto' }}>
                                    {renderTimeItems()}
                                </div>
                            </div>
                        </>
                    )}

                    {/* 订单摘要 */}
                    <div className="ap_order-summary">
                        <div className="ap_summary-item">
                            <span className="ap_summary-label">服务项目：</span>
                            <span className="ap_summary-value">{selectedService.name}</span>
                        </div>
                        <div className="ap_summary-item">
                            <span className="ap_summary-label">预约日期：</span>
                            <span className="ap_summary-value">{selectedCalendarDate || '未选择'}</span>
                        </div>
                        <div className="ap_summary-item">
                            <span className="ap_summary-label">预约时段：</span>
                            <span className="ap_summary-value">{selectedTime || '未选择'}</span>
                        </div>
                        <div className="ap_summary-total">
                            <span className="ap_total-label">应付金额：</span>
                            <span className="ap_total-value">¥{selectedService.discountPrice}</span>
                        </div>
                    </div>

                    {/* 提交按钮 */}
                    <div className="ap_action-area">
                        <div
                            className={`ap_submit-btn ${isSubmitting ? 'ap_submit-loading' : ''}`}
                            onClick={handleSubmit}
                            disabled={isSubmitting || !selectedCalendarDate || !selectedTime}
                        >
                            {isSubmitting && <LoadingOutlined style={{ marginRight: '8px' }} spin />}
                            {isSubmitting ? '提交中...' : '确认预约并支付'}
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default Appointment;
    